import TitleBar from "@/components/TitleBar/TitleBar";
import { useState } from "react";
//导入uuid,生我们生成唯一的字符串
import { v4 as uuidv4 } from "uuid";

const Chat = () => {
    const [inputMsg, setInputMsg] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const [messageList, setMessageList] = useState([]);


    /**
     * 发送问题
     */
    const sendQuestion = () => {
        if (inputMsg.trim().length === 0) {
            return;
        }
        if (isLoading) {
            return;
        }
        setIsLoading(true);
        //第1步：构建消息
        let userMessage = {
            id: uuidv4(),
            role: "user",
            create_at: Date.now(),
            content: inputMsg
        }
        let assistantMessage = {
            id: uuidv4(),
            role: "assistant",
            create_at: Date.now(),
            content: ""
        }
        //这里有一个天大的坑
        //所有的状态操作都是异步的
        // setMessageList([...messageList, userMessage]);
        // setMessageList([...messageList,assistantMessage]);
        setMessageList((prevData) => {
            let newList = [...prevData];
            newList.push(userMessage);
            newList.push(assistantMessage);
            return newList;
        });

        //第2步：将消息发送到AI服务器
        let u = "http://www.softeem.xin:9898/baiduAPI/stream/chat";
        fetch(u, {
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8"
            },
            body: JSON.stringify({
                content: inputMsg
            })
        }).then(resp => {
            let reader = resp.body.getReader();
            let textDecoder = new TextDecoder();
            const processData = () => {
                reader.read().then(result => {
                    let text = textDecoder.decode(result.value);
                    let josnStr = text.replace(/data: /g, "").trim();
                    if (josnStr) {
                        let jsonObj = JSON.parse(josnStr);
                        console.log(jsonObj.result);
                        //将消息追加到最后一条的AI消息内容里面

                        setMessageList((prevData) => {
                            const newList = [...prevData];
                            const lastItem = newList[newList.length - 1];
                            return [
                                ...newList.slice(0, -1),
                                { ...lastItem, content: lastItem.content + jsonObj.result }
                            ]
                        })
                    }
                    if (!result.done) {
                        processData();
                    }
                });
            };
            processData();
        }).catch(error => {
            console.log(error);
        }).finally(() => {
            setIsLoading(false);
        });
        //将输入框清空
        setInputMsg("");
    }


    const buildMessageList = () => {
        return messageList.map(item => {
            if (item.role === "user") {
                return <UserMessageItem key={item.id} itemData={item} />
            }
            else if (item.role === "assistant") {
                return <AssistantMessageItem key={item.id} itemData={item} />
            }
        })
    }

    return <div className="w-full h-full overflow-auto flex flex-col">
        <TitleBar title="智能小助手" />
        <div className="flex-1 overflow-auto bg-[#EEEEEE] box-border px-[5px]">
            {buildMessageList()}
        </div>
        <div className="h-[50px] bg-white flex flex-row items-center box-border px-[10px] py-[5px] gap-[10px]">
            <input
                value={inputMsg}
                onInput={(event) => {
                    setInputMsg(event.target.value)
                }}
                type="text"
                placeholder="快来输入你的问题吧"
                className="box-border px-[4px] flex-1 outline-0 h-full bg-gray-100" />
            <span
                onClick={sendQuestion}
                className="iconfont icon-zhifeiji text-[26px] text-primary-color transition-all active:scale-90 active:text-green-400"></span>
        </div>
    </div>
}

/**
 * 用户消息
 */
const UserMessageItem = (props) => {
    return <div className="flex flex-row gap-[5px] my-[10px]">
        <div className="w-[45px]">

        </div>
        <div className="flex flex-col flex-1 gap-[5px] items-end overflow-auto">
            <div className="text-[12px] text-gray-700">{props.itemData.create_at}</div>
            <div className="bg-[#55B2FB] text-white text-[14px] leading-[22px] p-[6px] rounded-[6px]">
                {props.itemData.content}
            </div>
        </div>
        <div className="w-[45px]">
            <img
                className="w-[45px] h-[45px] rounded-full"
                src={new URL("@/assets/img/avatar.jpg", import.meta.url).href} alt="" />
        </div>
    </div>
}
export default Chat;